import { clear_gun, get_gun } from 'base/api';
import { g_psn, g_db, g_stepnum } from 'db/state';
import { put_log } from 'base/ctl/log';
import { msn_info } from 'use/info';
import { uReal, cline } from 'sui';

const do_scanin = (stepnum, step, umd, watch) => {
    const msn = get_gun(step);
    if (!msn) {
        watch.startWatch();
        return;
    }

    put_log("编码", msn, "扫描轴承编码");

    clear_gun();
    g_db.s_msn(msn);

    umd.set("msn", msn);

    const herr = (e) => {
        umd.setErr(e);
        watch.startWatch();
    };

    if (msn.length > 10) {
        return herr("条码位数错误");
    }

    const next = g_db.next();
    if (next !== msn) {
        return herr(`此编码与外圈不匹配，正确编码为: ${next}, 当前扫码为: ${msn}`);
    }

    const psn = g_psn();
    const box_sn = g_db.box();

    uReal(null, "pair/join",
        {
            line: cline(),
            k: psn,
            box: box_sn,
        },
        r => {
            const is_new = msn_info(psn);

            if (is_new) {
                let num = g_db.num() + 1;
                let sum = g_db.sum() + 1;

                g_db.s_num(num);
                g_db.s_sum(sum);

                umd.mset({
                    sum: sum,
                    num: num,
                });
            }

            umd.mset({
                err: "",
                next: "",
            });

            g_db.s_next("");

            const stepnum = g_stepnum();

            umd.set_st_num("scanout", stepnum - 1);
            watch.startWatch();
        },
        e => herr("产品号绑定箱号出错"));
};

const do_ngin = (stepnum, step, umd, watch) => {
    const msn = get_gun(step);
    if (!msn) {
        watch.startWatch();
        return;
    }

    put_log("编码", msn, "扫描轴承编码");

    clear_gun();
    g_db.s_msn(msn);

    umd.set("msn", msn);

    const herr = (e) => {
        umd.setErr(e);
        watch.startWatch();
    };

    if (msn.length > 10) {
        return herr("条码位数错误");
    }

    const next = g_db.next();
    if (next !== msn) {
        return herr(`此编码与外圈不匹配，正确编码为: ${next}, 当前扫码为: ${msn}`);
    }

    const psn = g_psn();

    uReal(null, "pair/ng",
        {
            line: cline(),
            k: psn,
        },
        r => {
            msn_info(psn);

            umd.mset({
                err: "",
                next: "",
            });

            g_db.s_next("");

            const stepnum = g_stepnum();

            umd.set_st_num("ngout", stepnum - 1);
            watch.startWatch();
        },
        e => herr("产品号绑定箱号出错"));
};

export {do_ngin, do_scanin};
